package com.yoooya.base.common;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.lang.reflect.Method;

/**
 * @创建人 Sun Yijing
 * @创建时间 2018-06-28
 */
public class TopicMessageListener implements MessageListener {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	public static final String TOPIC = "event:callSvc";

	@Autowired
	private StringRedisTemplate redisTemplate;

	@Override
	public void onMessage(Message message, byte[] pattern) {
		logger.debug("Receive message[{}, {}]", message, pattern);
		byte[] body = message.getBody();
		byte[] channel = message.getChannel();
		String topic = redisTemplate.getStringSerializer().deserialize(channel);
		String msg = (String) redisTemplate.getValueSerializer().deserialize(
				body);
		switch (topic) {
		case TOPIC:
			executeSvc(msg);
			break;
		default:
			logger.warn("Illegal message[{}, {}]", topic, msg);
		}
	}

	private void executeSvc(String param) {
		String[] params = StringUtils.split(param, ",", 3);
		if (ArrayUtils.isNotEmpty(params) && params.length > 1) {
			try {
				String bean = StringUtils.trim(params[0]);
				Class clazz = Class.forName(bean);
				Object obj;
				try {
					obj = SpringContextHelper.getBean(clazz);
				} catch (NoSuchBeanDefinitionException e) {
					obj = clazz.newInstance();
				}

				if (params.length == 2) {
					Method method = clazz.getDeclaredMethod(StringUtils
							.trim(params[1]));
					method.invoke(obj);
				} else {
					Method method = clazz.getDeclaredMethod(
							StringUtils.trim(params[1]), String.class);
					method.invoke(obj, StringUtils.trim(params[2]));
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		} else {
			logger.warn("Illegal message[{}]", param);
		}
	}
}
